<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Config;
use app\common\model\CourseList;
use app\common\model\GroupWork;
use app\common\model\User;
use app\common\model\Order;
use fast\Random;
use think\Db;
use think\Validate;
require_once "wxpay/lib/WxPay.Api.php";
require_once "wxpay/example/WxPay.Config.php";
require_once "wxpay/example/WxPay.JsApiPay.php";

class Response extends Api
{
    public function response (){
        $data    = file_get_contents('php://input');
        $data = $this->xml_to_data($data);
        // sign不参与签名算法
        $data_sign = $data['sign'];
        unset($data['sign']);
        $sign = $this->makeSign($data);
        /* $sign = 1;
         $data_sign = 1;
         $data = [
             'return_code'=>'SUCCESS',
             'result_code'=>'SUCCESS',
             'out_trade_no'=>'A1186008283942',
         ];*/
        // 判断签名是否正确 判断支付状态
        if (($sign===$data_sign) && ($data['return_code']=='SUCCESS') && ($data['result_code']=='SUCCESS') ) {
            $goods_order = Order::where('order_sn',$data['out_trade_no'])->find();
            if($goods_order && $goods_order['status'] ==0){
                //如果是购买商品订单
                //更改订单状态
                Db::startTrans();
                $res = Order::where('order_sn',$data['out_trade_no'])->update(['status'=>1,'paytime'=>time()]);
                if($res){
                    //查看是什么类型的订单0普通课程，1拼团课程，2体验课程
                    if($goods_order['type'] == 0){
                        //课程信息
                        $goods_info = CourseList::where('id',$goods_order['kecheng_id'])->find();
                        if($goods_info['share_num'] >0 && $goods_info['giveaway'] != ''){
                            //如果该课程设置了分享购买人数及赠送礼品，判断分享人的数量是否达到标准，如果达到，赠送分享人礼品
                            if($goods_order['share_id']){
                                $share_info = User::where('id',$goods_order['share_id'])->find();
                                //购买人信息
                                $buyer_info = User::where('id',$goods_order['userid'])->find();
                                if($buyer_info['parent_id'] == $share_info['id']){
                                    //当分享人是购买人的上级时赠送规则才触发
                                    //如果分享人存在。添加分享记录
                                    $share_count = Db::name('share_info')->where('share_id',$goods_order['share_id'])->where('kecheng_id',$goods_info['id'])->count();
                                    if($share_count){
                                        Db::name('share_info')->where('share_id',$goods_order['share_id'])->where('kecheng_id',$goods_info['id'])->setInc('num',1);
                                    }else{
                                        Db::name('share_info')->insert(['share_id'=>$goods_order['share_id'],'kecheng_id'=>$goods_info['id'],'num'=>1,'createtime'=>time()]);
                                    }
                                    $share_count1 = Db::name('share_info')->where('share_id',$goods_order['share_id'])->where('kecheng_id',$goods_info['id'])->value('num');
                                    if($share_count1 == $goods_info['share_num']){
                                        $res1 =  Db::name('giveaway_list')->insert(['userid'=>$share_info['id'],'name'=>$goods_info['giveaway'],'createtime'=>time()]);
                                        Db::name('share_info')->where('share_id',$goods_order['share_id'])->where('kecheng_id',$goods_info['id'])->delete();
                                    }
                                }
                            }
                        }
                    }elseif($goods_order['type'] == 1){
                        //拼团课程
                        //查找该拼团信息，
                        $group_work = GroupWork::where('id',$goods_order['group_work_id'])->find();
                        if($group_work){
                            //查看该团是否已经拼成或者人数是否已经足够
                            if($group_work['status'] == 2 || $group_work['status'] == 3 || ($group_work['total_num'] == $group_work['num'])){
                                //如果已经该团已经拼团成功，则给用户发起退款，且把支付状态改为已取消
                                //$user_info = User::where('id',$goods_order['userid'])->value('openid');
                                $this->refund_order($goods_order['order_sn'],$goods_order['price'],$goods_order['price']);
                                Order::where('id',$goods_order['id'])->update(['status'=>2]);
                            }else{
                                //否则把该拼团人数+1
                                GroupWork::where('id',$group_work['id'])->setInc('num',1);
                                //如果该团的状态为待成团，状态改为拼团中
                                if($group_work['status'] == 0){
                                    GroupWork::where('id',$group_work['id'])->update(['status'=>1]);
                                }else{
                                    if($group_work['total_num'] == ($group_work['num']+1)){
                                        //如果该团人数已经达到，把该拼团状态设为已拼成
                                        GroupWork::where('id',$group_work['id'])->update(['status'=>2]);
                                    }
                                }
                            }
                        }
                    }
                }
                Db::commit();
                return 'SUCCESS';
            }
        }else{
            return 'FALL';
        }
    }
    public function xml_to_data($xml){
        if(!$xml){
            return false;
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $data;
    }
    /**
     * 接收通知成功后应答输出XML数据
     * @param string $xml
     */
    public function replyNotify(){
        $data['return_code'] = 'SUCCESS';
        $data['return_msg'] = 'OK';
        $xml = $this->data_to_xml( $data );
        echo $xml;
        die();
    }

    function data_to_xml($arr){
        $xml = "<root>";
        foreach ($arr as $key=>$val){
            if(is_array($val)){
                $xml.="<".$key.">".data_to_xml($val)."</".$key.">";
            }else{
                $xml.="<".$key.">".$val."</".$key.">";
            }
        }
        $xml.="</root>";
        return $xml;
    }

    /**

     * 生成签名

     * @return 签名，本函数不覆盖sign成员变量

     */
    protected function makeSign($data){
        //获取微信支付秘钥
        //require_once "wxpay/lib/WxPay.Api.php";
        $key = '99hRRIVCjpjCX92t5FmxzMyV0CT6PGRL';
        // 去空
        $data=array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a=http_build_query($data);
        $string_a=urldecode($string_a);
        //签名步骤二：在string后加入KEY
        //$config=$this->config;
        $string_sign_temp=$string_a."&key=".$key;
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result=strtoupper($sign);
        return $result;
    }
    public function wx_pay($order_number,$price,$openid){
        // vendor('Qiniu.autoload');
        require_once "wxpay/lib/WxPay.Api.php";
        require_once "wxpay/example/WxPay.Config.php";
        require_once "wxpay/example/WxPay.JsApiPay.php";
        $tools = new \JsApiPay();
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("订单信息");
        $input->SetAttach("test");
        $input->SetOut_trade_no($order_number);//订单号
        $input->SetTotal_fee($price*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url($this->domain . "/api/response/response");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $config = new \WxPayConfig();
        $order = \WxPayApi::unifiedOrder($config, $input);
        //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        //print_r($order);exit;
        $jsApiParameters = $tools->GetJsApiParameters($order);
        return $jsApiParameters;
    }
    public function refund_order($out_trade_no,$total_fee,$refund_fee){
        $input = new \WxPayRefund();
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($total_fee);
        $input->SetRefund_fee($refund_fee);
        $config = new \WxPayConfig();
        $input->SetOut_refund_no("sdkphp".date("YmdHis"));
        $input->SetOp_user_id($config->GetMerchantId());
        $result = \WxPayApi::refund($config, $input);
        return $result;
    }
}
